#!/usr/bin/python
#coding:utf-8

from multiprocessing.connection import Listener
from multiprocessing.connection import Client
from send_mail import sendmail
from datetime import datetime, date
import redis
import json
import urllib
import urllib2
import daemon
import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config.tdm_config import *

ALERT_DEBUG = True

def alert_daemon():
    address = ('localhost', tdm_alert_localport)     # family is deduced to be 'AF_INET'
    listener = Listener(address, authkey=tdm_alert_authkey)

    while True:
        conn = listener.accept()
        dt = datetime.now()

        if ALERT_DEBUG:
            print 'connection accepted from', listener.last_accepted
            print 'datetime:', dt

        login, mail, phones = conn.recv()
        conn.close()

        if ALERT_DEBUG:
            print 'LOGIN:', login
            print 'MAIL:', mail
            print 'PHONES:', phones

        # sendmail for alert
        ret = sendmail(login, mail)
        if ALERT_DEBUG:
            print ret

        if tdm_alert_sms and phones and (dt.hour > 5 and dt.hour < 22):
            sms = {
                'msg': mail['content'],
                'city': '010',
                'phone': phones
            }
            data = urllib.urlencode(sms)
            if ALERT_DEBUG:
                print data
            req = urllib2.Request(tdm_alert_sms_url, data)
            response = urllib2.urlopen(req, timeout=5)
            if ALERT_DEBUG:
                print response.read()
            
    listener.close()

def client_send(login, mail, phones):
    try:
        address = ('tdm-mail', tdm_alert_localport)
        conn = Client(address, authkey=tdm_alert_authkey)
        conn.send((login, mail, phones))
        conn.close()
    except Exception as e:
        print "error: %s" % (str(e))

if __name__ == '__main__':
    #with daemon.DaemonContext():
    while True:
        try:
            alert_daemon()
        except Exception as e:
            err_msg = "error: %s" % (str(e))
            print err_msg

